package com.study.system.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * JWT用户认证的工具类
 */
public class JWTUtil {

    private static final String SIGN = "COMMUNITY_MANAGEMENT_SYSTEM";

    /**
     * 生成token
     */
    public static String getToken(Map<String, String> claims) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);  // 默认7天有效时间

        // 创建JWT Builder
        JWTCreator.Builder builder = JWT.create();

        // 设置payload
        for (Map.Entry<String, String> entry : claims.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            builder.withClaim(key, value);
        }

        // 指定有效时间
        builder.withExpiresAt(instance.getTime());

        // 设置签名
        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 验证token
     */
    public static DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

}
